// listenerManager.js
const { registerHandler, unregisterHandler ,messageSnedUserHandler} = require('../messageRouter');
const GroupMessageListener = require('../GroupMessageListener');
const MAXSIZE = 20;
const listeners = [];

async function addListenes({ id, title, accessHash, client, phone }) {
  if (listeners.length >= MAXSIZE) return '监听组已达上限';
  if (listeners.some(l => l.id.toString() === id.toString())) return '已存在监听';

  const listenerClient = new GroupMessageListener(client, id, accessHash);
  const listene = { id, title, accessHash, client, phone, listenerClient,client };
  listeners.push(listene);
  return '添加成功';
}

function getListenerClientById(id) {
  const l = listeners.find(l => l.id.toString() === id.toString());
  return l ? l : null;
}

function getListenes() {
  return listeners.map(item => ({
    id: item.id.toString(),
    title: item.title,
    accessHash: item.accessHash.toString(),
    phone: item.phone,
    state: item.listenerClient.isListening()
  }));
}
async function listenerStart(obj) {
  const listenerClient = obj.listenerClient;
  if (listenerClient.isListening()) {
    console.log(`监听器 ${listenerClient.channelId} 已经在运行中`);
    return;
  }

  // 启动监听器（只添加一次全局监听）
  await listenerClient.start();
  // 注册该群组的事件处理器
  registerHandler(listenerClient.channelId, async (event) => {
    try {
      // console.log(event)
      const msg = event.message.message;
      const fromId = event.message.fromId;
      const peerId = event.message.peerId;

      if (!fromId || !fromId.userId) {
        console.log("⚠️ 来自匿名或系统用户，跳过处理");
        return;
      }

      const userId = fromId.userId.value;
      const channelId = peerId?.channelId?.value;

      // console.log("用户ID：", userId);
      // console.log("channelId：", channelId);

      const participants = await obj.client.getParticipants(channelId);
      // let userclient = await obj.client

      let userItem = {
        id: userId,
        accessHash: ""
      };

      for (const p of participants) {
        if (p.id?.value === userId) {
          userItem.accessHash = p.accessHash?.value;
          break;
        }
      }

      // console.log("👤 用户信息：", userItem);
      console.log(`📨 来自 ${userId} 的消息：${msg}`);
      let group = getListenerClientById(channelId)
      messageSnedUserHandler(msg,userItem.id,userItem.accessHash,group.title,channelId,obj.client)

      // if (msg.includes('测试')) {
      //   console.log('🎯 关键词命中：测试');
      //   // await sendPrivateMessageToUser(obj.client, userId, userItem.accessHash, "自动回复内容");
      // }



    } catch (err) {
      console.error(`❌ 消息处理错误（群组 ${listenerClient.channelId}）：`, err);
    }
  });

  console.log(`🚀 启动监听群组 ${listenerClient.channelId}`);
}


async function listenerStop(obj) {
  if (!obj.listenerClient.isListening()) return;
  unregisterHandler(obj.listenerClient.channelId);
  obj.listenerClient.started = false;
  console.log(`🛑 停止监听群组 ${obj.listenerClient.channelId}`);
}

function getSizeInfo(){
  
  let info = {
    maxsize : MAXSIZE,
    size :listeners.length
  }
  return info
}

async function delListener(id) {
  const index = listeners.findIndex(l => l.id.toString() === id.toString());

  if (index === -1) {
    return '未找到对应监听器';
  }

  const target = listeners[index];
  const listenerClient = target.listenerClient;

  if (listenerClient && listenerClient.isListening()) {
    // 仅在监听器运行时才执行停止逻辑
    unregisterHandler(listenerClient.channelId);
    listenerClient.started = false;
    console.log(`已停止监听群组 ${listenerClient.channelId}`);
  } else {
    console.log(`群组 ${target.id} 当前未在监听，无需停止`);
  }

  listeners.splice(index, 1);
  return `已移除监听器：群组 ${target.id}`;
}


module.exports = {
  addListenes,
  getListenerClientById,
  getListenes,
  listenerStart,
  listenerStop,
  getSizeInfo,
  delListener
};